package kitwee.com.kanpad.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;


import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.jianghu.protocol.xiongtian.MeterOutputCollection;
import com.jianghu.protocol.xiongtian.SheetsOutputCollection;
import com.jianghu.protocol.xiongtian.SpeedCollection;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;

import kitwee.com.kanpad.MyMultiDexApplication;

/**
 * Created by sven on 2017/6/22.
 */

public class PushService extends Service {
    private final IBinder mBinder = new PushBinder();


    @Override
    public void onCreate() {
        super.onCreate();


    }

    public static final int PORT = 5020;//监听的端口号
    private int TIMEOUT = 2000;//socketserver 超时时间

    public void init() {
        try {
            LogUtils.e("服务启动");
//            ToastUtils.showShort("服务启动: " );
            ServerSocket serverSocket = new ServerSocket(PORT);
//            serverSocket.setSoTimeout(TIMEOUT);
            while (true) {
                Socket clientSocket = null;
                // 一旦有堵塞, 则表示服务器与客户端获得了连接
                clientSocket = serverSocket.accept();//获得客户端的请求的Socket
//                ToastUtils.showShort("服务器连接成功: " );
//                clientSocket.setSoTimeout(2000);//客戶端
                // 处理这次连接
                new HandlerThread(clientSocket);
            }
        } catch (Exception e) {
//            ToastUtils.showShort("服务器异常: " + e.getMessage());
            System.out.println("服务器异常: " + e.getMessage());
        }
    }

    private boolean ISMETER = false;

    private Map<String,Map<String, Integer>> finalMap=new LinkedHashMap<>();

    private class HandlerThread implements Runnable {
        private java.net.Socket socket;

        public HandlerThread(java.net.Socket client) {
            socket = client;
            new Thread(this).start();
        }

        public void run() {
            DataOutputStream out = null;
            DataInputStream input = null;
            try {
                out = new DataOutputStream(socket.getOutputStream());
                System.out.println("请输入:");
                out.write(SheetsOutputCollection.COMMAND);
                out.flush();
                input = new DataInputStream(socket.getInputStream());
                byte[] byteArray = new byte[1024];
                int arrayLength = input.read(byteArray);
                byte[] newByteArray = new byte[arrayLength];
                System.arraycopy(byteArray, 0, newByteArray, 0, arrayLength);
                LogUtils.e("sheet 读写");
                Map<String, Integer> returnMapSheet = SheetsOutputCollection.decode(newByteArray);
                finalMap.put("sheet",returnMapSheet);
                out.write(MeterOutputCollection.COMMAND);
                out.flush();
                byteArray= new byte[1024];
                arrayLength = input.read(byteArray);
                newByteArray = new byte[arrayLength];
                System.arraycopy(byteArray, 0, newByteArray, 0, arrayLength);
                LogUtils.e("meter 读写");
                Map<String, Integer> returnMapMeter = MeterOutputCollection.decode(newByteArray);
                finalMap.put("meter",returnMapMeter);
                out.write(SpeedCollection.COMMAND);
                out.flush();
                byteArray= new byte[1024];
                // 读取客户端数据
                arrayLength = input.read(byteArray);
                newByteArray = new byte[arrayLength];
                System.arraycopy(byteArray, 0, newByteArray, 0, arrayLength);
                LogUtils.e("speed 读写");
                Map<String, Integer> returnMapSpeed = SpeedCollection.decode(newByteArray);
                finalMap.put("speed",returnMapSpeed);
                callBacks.onDataChanged(finalMap);
                Thread.sleep(100);
            } catch (Exception e) {
//                ToastUtils.showShort("服务器异常: " + e.getMessage());
                System.out.println("服务器 run 异常: " + e.getMessage());
            } finally {
                if(finalMap.size()>0){
                    finalMap.clear();
                }
                if (input != null) {
                    try {
                        input.close();
                        LogUtils.e("input close");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (out != null) {
                    try {
                        out.close();
                        LogUtils.e("out close");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (socket != null) {
                    try {
                        socket.close();
                        LogUtils.e("socket close");
//                        ToastUtils.showShort("socket:关闭 " );
                    } catch (Exception e) {
                        socket = null;
//                        ToastUtils.showShort("服务端 finally 异常: " + e.getMessage());
                        System.out.println("服务端 finally 异常:" + e.getMessage());
                    }
                }
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread() {
            @Override
            public void run() {
                super.run();
//                SocketServerUtils.newInstance();
                init();
            }
        }.start();
        return super.onStartCommand(intent, flags, startId);

    }


    public static void start(Context context) {
        if (context == null) {
            throw new NullPointerException("Context can not be null!");
        }
        Intent intent = new Intent(context, PushService.class);
        context.startService(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();


    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class PushBinder extends Binder {
        public PushService getPushService() {
            return PushService.this;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    /**
     * 重启服务
     */
    public static void restart() {
        stop(MyMultiDexApplication.getContext());
        start(MyMultiDexApplication.getContext());
    }

    public static void stop(Context context) {
        if (context == null) {
            throw new NullPointerException("Context can not be null!");
        }
        Intent intent = new Intent(context, PushService.class);
        context.stopService(intent);
        LogUtils.e("关闭了连接");
    }

    public static interface SocketCallBack {
        //        void onDataChanged(String dataName,String data);
        void onDataChanged(Map<String, Map<String ,Integer>> returnMap);

    }

    private SocketCallBack callBacks;

    public void registerCallBack(SocketCallBack callBack) {
        this.callBacks = callBack;
    }


}
